//
// Created by hkkzzxz on 24-9-7.
//

#include "SendHttp.h"

http::response<http::dynamic_body>
SendHttp::sendRequest(http::request<http::dynamic_body> &httpRequest) {

    http::response<http::dynamic_body> httpResponse;

    try {
        // 设置HTTP请求的主机， 用户代理字段
        httpRequest.set(http::field::host, host);
        httpRequest.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);

        // 解析主机名和端口以获取服务器的IP地址
        net::io_context ioc;
        tcp::resolver resolver{ioc};
        beast::tcp_stream stream{ioc};
        auto const results = resolver.resolve(host, port);

        // 发送HTTP请求
        beast::error_code ec;
        stream.connect(results, ec);
        if (ec) {
            throw std::runtime_error("Connect error: " + ec.message());
        }
        http::write(stream, httpRequest, ec);
        if (ec) {
            throw std::runtime_error("Write error: " + ec.message());
        }

        // 接受响应，并关闭socket
        beast::flat_buffer buffer;
        http::read(stream, buffer, httpResponse, ec);
        if (ec) {
            throw std::runtime_error("Read response error: " + ec.message());
        }
        stream.socket().shutdown(tcp::socket::shutdown_both, ec);
        // 如果发生错误且不是连接断开，抛出异常
        if (ec && ec != beast::errc::not_connected) {
            throw std::runtime_error("Not connected error: " + ec.message());
        }
        consoleLogger->info("Send http request success");
    }
    catch (std::exception const &e) {
        consoleLogger->error("Send http request error: {}", e.what());
        fileLogger->error("Send http request error: {}", e.what());
        httpResponse.result(http::status::service_unavailable);
        httpResponse.set(http::field::content_type, "text/plain");
        beast::ostream(httpResponse.body()) << "Service unavailable: " << e.what();
    }

    return httpResponse;
}
